package com.ljq.epidemic.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class JsonReader {

    public static String fromURL(String urlStr){
        HttpURLConnection connection;
        InputStream is;
        BufferedReader br;

        StringBuilder builder = new StringBuilder();

        try {
            URL url = new URL(urlStr);

            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");

            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);

            connection.setRequestProperty("accept","application/json");

            connection.connect();

            if(connection.getResponseCode() == 200){
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is,"UTF-8"));

                String line = br.readLine();
                while(line != null){
                    builder.append(line);
                    line = br.readLine();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return builder.toString();
    }

    public static String fromFile(String filePath){
        File file = new File(filePath);
        FileReader reader = null;

        StringBuilder builder = new StringBuilder();

        try {
            reader = new FileReader(file);
            char[] chars = new char[1024];
            int count = reader.read(chars);

            while (count > 0) {
                builder.append(chars, 0, count);
                count = reader.read(chars);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return builder.toString();
    }

}
